<!-- components/multi-select-popup/multi-select-popup.vue -->
<template>
	<view class="multi-select-container">
		<!-- 标签展示区域 -->
		<view class="tags-box" :class="{ disabled: disabled }" @click="handleContainerClick">
			<view v-if="selectedLabels.length" class="tags-wrapper">
				<view v-for="(label, index) in displayTags" :key="index" class="tag-item">
					<text class="tag-text">{{ label }}</text>
					<view v-if="showClose" class="tag-close" @click.stop="handleRemoveTag(index)">
						<uni-icons type="closeempty" size="12" color="#999" />
					</view>
				</view>
				<view v-if="exceedCount > 0" class="more-tag">
					+{{ exceedCount }}
				</view>
			</view>
			<text v-else class="placeholder">{{ placeholder }}</text>
			<uni-icons v-if="!disabled" type="arrowdown" size="16" class="arrow-icon"
				:color="disabled ? '#ccc' : '#666'" />
		</view>

		<!-- 弹窗内容 -->
		<uni-popup ref="popup" type="dialog">
			<view class="popup-content">
				<view class="popup-header">
					<text class="title">{{ title }}</text>
					<uni-icons type="close" size="20" color="#999" @click="handleCancel" />
				</view>

				<scroll-view scroll-y class="option-list">
					<checkbox-group @change="handleSelectChange">
						<label v-for="(item, index) in processedOptions" :key="`option_${index}_${item.value}`"
							class="option-item">
							<!-- 修改checkbox组件部分 -->
							<checkbox :value="String(item.value)" :checked="tempSelected.includes(String(item.value))"
								:disabled="item.disabled"  class="checkbox"
								:class="{checked: tempSelected.includes(String(item.value))}" />
							<text class="option-label"> {{ item.value }} {{ item.label }} </text>
						</label>
					</checkbox-group>
				</scroll-view>

				<view class="popup-footer">
					<button class="btn cancel-btn" @click="handleCancel">取消</button>
					<button class="btn confirm-btn" @click="handleConfirm">确定</button>
				</view>
			</view>
		</uni-popup>
	</view>
</template>

<script>
	export default {
		name: 'MultiSelectPopup',
		props: {
			// 选项列表
			options: {
				type: Array,
				default: () => []
			},
			// 选中的值
			value: {
				type: Array,
				default: () => []
			},
			// 最大显示标签数
			maxDisplay: {
				type: Number,
				default: 3
			},
			// 弹窗标题
			title: {
				type: String,
				default: '请选择'
			},
			// 占位符
			placeholder: {
				type: String,
				default: '请选择'
			},
			// 是否禁用
			disabled: {
				type: Boolean,
				default: false
			},
			// 确认按钮颜色
			checkedColor: {
				type: String,
				default: '#1890ff'
			},
			// 标签是否显示关闭按钮
			showClose: {
				type: Boolean,
				default: true
			},
			// 值字段名
			valueKey: {
				type: String,
				default: 'value'
			},
			// 显示字段名
			labelKey: {
				type: String,
				default: 'label'
			}, labels: {
    type: String,
    default: ''
  }
		},
		data() {
			return {
				tempSelected: [],
				isPopupOpen: false
			}
		},
		computed: {
			// 处理后的选项数据
			processedOptions() {
				return this.options.map(item => ({
					label: item[this.labelKey],
					value: String(item[this.valueKey]), // 强制转为字符串
					disabled: item.disabled || false
				}))
			},
  selectedLabelsString() {
    return this.processedOptions
      .filter(item => this.tempSelected.includes(String(item.value)))
      .map(item => item.label)
      .join(',')
  },
			// 当前选中的标签文本
			selectedLabels() {
				return this.processedOptions
					.filter(item =>
						this.value.map(String).includes(String(item.value))
					)
					.map(item => item.label)
			},

			// 实际显示的标签（考虑最大显示数量）
			displayTags() {
				return this.selectedLabels.slice(0, this.maxDisplay)
			},

			// 超出显示的标签数量
			exceedCount() {
				return Math.max(this.selectedLabels.length - this.maxDisplay, 0)
			}
		},
		watch: {
			value: {
				immediate: true,
				handler(newVal) {
					// 统一转换为字符串数组
					this.tempSelected = Array.isArray(newVal) ?
						newVal.map(String) : []
				}
			}
		},
		methods: {
			// 点击容器
			handleContainerClick() {
				if (this.disabled) return
				this.tempSelected = [...this.value]
				this.$refs.popup.open()
			},

			// 删除标签
			handleRemoveTag(index) {
				if (this.disabled) return
				const newValue = [...this.value]
				newValue.splice(index, 1)
				this.$emit('input', newValue)
			},

			// 选项变化
			// 在handleSelectChange方法中强制转换类型
			handleSelectChange(e) {
				this.tempSelected = (e.detail.value || [])
					.map(v => String(v)); // 确保转换为字符串
				console.log('当前选中:', this.tempSelected); // 调试日志
			},

			// 确认选择
			handleConfirm() {
				// 确保发送字符串数组
				 const labelsString = this.selectedLabelsString // 获取拼接后的字符串
				this.$emit('input', [...this.tempSelected])
				  this.$emit('update:labels', labelsString) // 新增自定义事件
				this.$refs.popup.close()
			},

			// 取消选择
			handleCancel() {
				this.tempSelected = [...this.value]
				this.$refs.popup.close()
			}
		}
	}
</script>

<style lang="scss" scoped>
	.multi-select-container {
		position: relative;
		font-size: 14px;
	}

	.tags-box {
		min-height: 40px;
		padding: 8px 35px 8px 12px;
		border: 1px solid #dcdfe6;
		border-radius: 4px;
		background-color: #fff;
		position: relative;

		&.disabled {
			background-color: #f5f7fa;
			cursor: not-allowed;
		}
	}

	/* 修改样式穿透部分 */
	:deep(.uni-checkbox) {
		&.checked {

			/* 增加选中状态类 */
			.uni-checkbox-input {
				background-color: v-bind(checkedColor) !important;
				border-color: v-bind(checkedColor) !important;

				&::before {
					color: #fff !important;
				}
			}
		}

		.uni-checkbox-input {
			border-radius: 4px !important;
			transition: all 0.2s ease-in-out;

			/* 修正伪元素选择器 */
			&::before {
				font-size: 14px !important;
				line-height: 1;
			}
		}
	}

	.tags-wrapper {
		display: flex;
		flex-wrap: wrap;
		gap: 6px;
	}

	.tag-item {
		display: inline-flex;
		align-items: center;
		height: 24px;
		padding: 0 8px;
		background-color: #f0f2f5;
		border-radius: 4px;
		animation: tagIn 0.2s ease;
	}

	.tag-text {
		font-size: 12px;
		color: #333;
		max-width: 120px;
		white-space: nowrap;
		overflow: hidden;
		text-overflow: ellipsis;
	}

	.tag-close {
		margin-left: 4px;
		padding: 2px;
		border-radius: 50%;
		display: flex;
		align-items: center;

		&:active {
			background-color: #e5e5e5;
		}
	}

	.more-tag {
		height: 24px;
		line-height: 24px;
		padding: 0 6px;
		color: #999;
		font-size: 12px;
	}

	.placeholder {
		color: #c0c4cc;
		line-height: 24px;
	}

	.arrow-icon {
		position: absolute;
		right: 12px;
		top: 50%;
		transform: translateY(-50%);
	}

	.popup-content {
		width: 80vw;
		max-width: 400px;
		background: #fff;
		border-radius: 8px;
		overflow: hidden;
	}

	.popup-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 16px;
		border-bottom: 1px solid #eee;
	}

	.title {
		font-size: 16px;
		font-weight: 500;
		color: #333;
	}

	.option-list {
		max-height: 50vh;
		padding: 8px 0;
	}

	.option-item {
		display: flex;
		align-items: center;
		padding: 12px 16px;

		&:active {
			background-color: #f8f8f8;
		}
	}

	.checkbox {
		transform: scale(0.9);
	}

	.option-label {
		margin-left: 8px;
		color: #333;
	}

	.popup-footer {
		display: flex;
		justify-content: flex-end;
		gap: 12px;
		padding: 12px 16px;
		border-top: 1px solid #eee;
	}

	.btn {
		height: 32px;
		line-height: 32px;
		padding: 0 20px;
		font-size: 14px;
		border-radius: 4px;

		&.cancel-btn {
			background-color: #fff;
			border: 1px solid #dcdfe6;
			color: #666;
		}

		&.confirm-btn {
			background-color: #1890ff;
			color: #fff;
		}
	}

	@keyframes tagIn {
		from {
			opacity: 0;
			transform: translateY(4px);
		}

		to {
			opacity: 1;
			transform: translateY(0);
		}
	}
</style>